package com.heima.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.PageResult;
import com.heima.pojo.Node;
import com.heima.pojo.Region;
import com.heima.pojo.dto.RegionDto;
import com.heima.pojo.vo.RegionVo;
import com.heima.service.INodeService;
import com.heima.service.IRegionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 运营区域 前端控制器
 * </p>
 *
 * @author xjy
 * @since 2024-06-05
 */
@RestController
@RequestMapping("/vm-service/region")
@Api(tags = "运营区域管理")
public class RegionController {
    @Autowired
    private IRegionService regionService;
    @Autowired
    private INodeService nodeService;

    @GetMapping("/search")
    @ApiOperation("查询运营区域列表")
    public PageResult<RegionVo> search(PageResult<RegionVo> pageResult, @ApiParam(value = "区域名称", required = false) String name) {
        return regionService.search(pageResult, name);
    }

    @PostMapping
    @ApiOperation("添加运营区域")
    public Boolean addRegion(@RequestBody RegionDto regionDto) {
        if (ObjectUtil.isEmpty(regionDto)) {
            return false;
        }
        Region region = BeanUtil.toBean(regionDto, Region.class);
        region.setName(regionDto.getRegionName());
        return regionService.save(region);
    }

    @PutMapping("/{id}")
    @ApiOperation("修改运营区域")
    public Boolean updateRegion(@PathVariable @ApiParam(value = "区域id", required = true) Long id,
                                @RequestBody RegionDto regionDto) {
        if (ObjectUtil.isEmpty(regionDto) || ObjectUtil.isEmpty(id)) {
            return false;
        }
        LambdaUpdateWrapper<Region> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Region::getId, id);
        Region region = BeanUtil.toBean(regionDto, Region.class);
        region.setName(regionDto.getRegionName());
        return regionService.update(region, updateWrapper);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除运营区域")
    public Boolean deleteRegion(@PathVariable @ApiParam(value = "区域id", required = true) Long id) {
        if (ObjectUtil.isEmpty(id)) {
            return false;
        }
        LambdaQueryWrapper<Node> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Node::getRegionId, id);
        int count = nodeService.count(queryWrapper);
        if (count > 0) {
            return false;
        }
        return regionService.removeById(id);
    }
}
